<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="../less/upload-temp.css">
    <script src="../../src/lib/jquery.js"></script>
    <style>
        .demo{
            width:600px;
            height:500px;
            background-color:#dbdbdb;
            margin:0 auto;
        }
        .btn{
            display: inline-block;
            width: 100px;
            height:30px;
            border-radius: 5px;
            background-color: #1fb394;
            font-size: 14px;
            text-align: center;
            line-height: 30px;
            color:#fff;
        }
    </style>
</head>
<body>


<div class="demo">

    <form action="http://127.0.0.1/demo2.php" method="post" enctype="multipart/form-data">
        <ul data-name="upload" class="img-upload clearfix">
            <!--  <li class="upload-list">
                  <div class="list-layer"><i>&times;</i></div>
              </li>-->
            <li class="upload-list upload-add"></li>
        </ul>
        <button type="submit">go</button>
    </form>


    <div class="mt50">
        <span class="btn">点击上传</span>
    </div>

</div>

<script>


    //添加图片事件
    var num = 1;
    /**
     * 点击添加
     * 1 首先根据规则是否运行
     * 2 建立虚拟JQ对象并添加事件(input隐藏域)
     * 3 模拟点击后根据规则函数确定是否插入到真实dom树
     * */

    $('.upload-add').on('click',function(){
        var _this = $(this);
        var pr = _this.closest("[data-name='upload']");

        if(pr.find("[name='upload[]']").length >= 5){
            alert('The picture should be less than five');
            return;
        }
        var param = pr.attr('data-name') + "_" + num;

        //插入input
        var inputO = $("<input accept='image/jpg,image/jpeg,image/png' class='hide' type='file' name='upload[]' id='"+param+"'>");
            inputO.on('change',function(){
                var that = $(this);
                var mes = readFileRule(that,500);
                if(mes.type){
                    num++;
                    readFileUrl(that,pr);
                }else{
                    that.remove();
                    console.log(mes)
                }
            });
            inputO.trigger("click");
    });


    //删除事件
    $('body').on('click','.icon-remove',function(){
        var parent = $(this).parents('.upload-list');
        var id = parent.attr('data-name');
        $('#'+id).remove();
        parent.remove();
    });


    //校验图片格式
    function readFileRule(file,size){
        var file = file[0].files;
        var mes = {type:true,name:0};

        for(var i = 0;i<file.length;i++){
            if((file[i].size/1000)>size){
                mes.name = 1;mes.type = false;
                break;
            }else if(!/(jpeg)|(png)|(jpg)$/.test(file[i].type)){
                mes.name = 2;mes.type = false;
                break;
            }
        }
        return mes;
    }


    //读取临时文件
    function readFileUrl(input,pr){
        var inputObj = input;
        pr.append(inputObj);
        var template = '<li class="upload-list" data-name="'+inputObj.prop('id')+'">' +
                            '<div class="list-layer"><i class="icon-remove">&times;</i></div>' +
                       '</li>';
        var str = $(template);
        var reader = new FileReader();
            reader.readAsDataURL(inputObj[0].files[0]);
            reader.onload = function(){
                console.log(reader.result);
                str.css('background-image',"url("+reader.result+")");
                pr.find(".upload-add").before(str);
            };
    }

    $('.btn').on('click',function(){
        upLoad($("[name='upload[]']"),'')
    });

    function upLoad(inputObj,para){
        var fd = new FormData();
        inputObj.each(function(index,item){
            fd.append('upload[]',item.files[0])
        });
        fd.append("para",JSON.stringify(para));
        $.ajax({
            type : 'post',
            url : 'http://127.0.0.1/demo2.php',
            data : fd,
            cache : false,
            processData : false,
            contentType : false,
            success : function(){
                console.log('ok')
            },
            error : function(){
                console.log('err')
            }
        })
    }
</script>

</body>
</html>







<script>
    //图片读取
    /*for(var i = 0 ;i<file.length;i++){

     //console.log(file[i].name)

     var reader = new FileReader();

     reader.readAsDataURL(file[i]);

     reader.onload = function(){

     }
     //console.log(reader)
     }*/


    /*function upLoadImg(file,index){

     var fd = new FormData();

     fd.append('imgName',file[index])

     fd.append("para",JSON.stringify({name:'小明',age:12}));


     var xhr = new XMLHttpRequest();

     xhr.onreadystatechange = function(){

     if(xhr.readyState==1){

     console.log('准备发送')

     }

     if (xhr.readyState==4){

     if (xhr.status==200){

     if(xhr.responseText == 1){

     console.log('ok')

     }else{

     alert('服务错误')
     }

     }else{}
     }
     }

     xhr.open("POST",'http://192.168.0.100/demo.php');

     xhr.send(fd);

     //xhr.upload.addEventListener("progress", uploadProgress, false);

     }*/
</script>